import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.proxy.Proxy;
import us.codecraft.webmagic.proxy.SimpleProxyProvider;

public class GithubRepoPageProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000)
    		.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");

    @Override
    public void process(Page page) {
    	if(!page.getUrl().toString().startsWith("https://github.com/code4craft")){
    		//skip为true，则不会通知pipeline处理
    		page.setSkip(true);
    	}
    	page.addTargetRequests(page.getHtml().links().regex("https://github\\.com/code4craft.*").all());
    }

    @Override
    public Site getSite() {
    	//header、cookie在Site对象里面设置
        return site;
    }

    public static void main(String[] args) {
        Spider spider = Spider.create(new GithubRepoPageProcessor()).addUrl("https://github.com/code4craft").thread(1);
        HttpClientDownloader downloader = new HttpClientDownloader(){
			@Override
			protected void onError(Request request) {
				setProxyProvider(SimpleProxyProvider.from(new Proxy("10.10.10.10", 8888)));
			}
		};
		spider.setDownloader(downloader);
    }
}